import React, { useEffect, useState } from 'react';
import { Dialog, Input, Button, Switch } from '@alifd/next';
import { useStore } from '@/hooks';
import TauSimpleSelect from '@/components/TauSimpleSelect';
import { t } from '@lingui/macro';

const CompanyInputDialog = ({ visible, info, modal, onClose, onConfirm }) => {
  const [companyName, setCompanyName] = useState('');
  const [currentCompanyName, setCurrentCompanyName] = useState(false);
  const [saveVehicle, setSaveVehicle] = useState(true);
  const [transform, setTransform] = useState(() => modal === 'add');
  const { memberStore: store } = useStore();

  useEffect(() => {
    setCompanyName(() => info?.companyName || '');
    setCurrentCompanyName(() => info?.companyName || '');
    return () => {
      setCompanyName('');
      setTransform(false);
    };
  }, [visible]);

  const handleConfirm = () => {
    onConfirm({ companyName: companyName || '', saveVehicle });
  };

  const handleTransform = () => {
    setCompanyName('');
    setTransform(() => !transform);
  };

  const titleComponent = (
    <div style={{ marginBottom: 10 }}>
      <span><strong>{t`备案提示：${info?.recordRemarks}`}</strong></span>
    </div>
  );

  const saveVehicleComponent = (
    <div style={{ marginBottom: 10 }}>
      <strong>{t`是否保留报备车辆信息：`}</strong>
      <Switch
        checked={saveVehicle}
        checkedChildren={t`是`}
        unCheckedChildren={t`否`}
        autoWidth
        onChange={(v) => handleOnSaveVehicle(v)}
        size="small"
      />
    </div>
  );

  const handleOnSaveVehicle = (e) => {
    setSaveVehicle(e);
  };

  return (
    <Dialog
      title={transform ? t`添加公司` : t`选择所属公司`}
      visible={visible}
      onOk={handleConfirm}
      onCancel={onClose}
      onClose={onClose}
      style={{ width: 300 }}
      footer={
        <>
          <Button type="primary" onClick={handleTransform}>{transform ? t`选择公司` : t`手动输入`}</Button>
          <Button style={{ marginLeft: 5 }} type="primary" onClick={handleConfirm}>{t`确定`}</Button>
          <Button style={{ marginLeft: 5 }} onClick={onClose}>{t`取消`}</Button>
        </>
      }
    >
      {titleComponent}
      {!currentCompanyName && companyName && saveVehicleComponent}
      {transform ?
        <Input
          value={companyName}
          onChange={(e) => setCompanyName(e)}
          placeholder="请输入公司名称"
          style={{ width: 260 }}
        />
        :
        <TauSimpleSelect
          value={companyName}
          dataSource={store.companiesNames}
          onChange={(e) => setCompanyName(e)}
          placeholder="请选择所属公司"
          style={{ width: 260 }}
        />}
    </Dialog>
  );
};

export default CompanyInputDialog;
